<?php
/**
 * Created by PhpStorm.
 * User: CCA
 * Date: 2019/9/25
 * Time: 16:53
 */

namespace app\admin\controller;


use app\common\model\AnswerMethod;
use app\common\model\QuestionOption;
use think\console\command\Lists;
use think\Lang;
use app\common\model\Goodsclass;
use think\Request;

class Question extends AdminControl
{
    public function _initialize() {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/'.config('default_lang').'/question.lang.php');
    }

    public function uniqueQuestion()
    {
        $title = input('post.title', '');
        $question = \app\common\model\Question::where('title', '=', $title)->find();
        if ($question) {
            return json(['code' => 10000, 'message' => '已存在该问题']);
        }

        return json(['code' => 0, 'message' => '']);
    }

    public function index(){
        $questionModel = new \app\common\model\Question();
        $title = input('get.title', '');
        $search_status = input('get.search_status', '');
        $search_gc_id1 = input('get.search_gc_id1', '');
        $search_gc_id2 = input('get.search_gc_id2', '');
        $search_gc_id3 = input('get.search_gc_id3', '');
        $condition = [];
        if ($title) {
            $condition['title'] = array('like', "%" . $title . "%");
        }
        if ($search_status) {
            if ($search_status == 2) $search_status = 0;
            $condition['status'] = ['eq', $search_status];
        }
        if ($search_gc_id1) {
            $condition['gc_id1'] = ['eq', $search_gc_id1];
        }
        if ($search_gc_id2) {
            $condition['gc_id2'] = ['eq', $search_gc_id2];
        }
        if ($search_gc_id3) {
            $condition['gc_id3'] = ['eq', $search_gc_id3];
        }

        $question_list = $questionModel->getQuestionList($condition,10);
//        var_dump($question_list);die;
        $class = new Goodsclass();
        $parent_class_list = $class->getGoodsclassList(['gc_parent_id'=>0]);
        $this->assign('class_list',$parent_class_list);

        $this->assign('question_list',$question_list);
        $this->assign('show_page', $questionModel->page_info->render());
        $this->assign('questionModel', $questionModel);

        $this->setAdminCurItem('index');
        return $this->fetch();
    }

    public function add(Request $request){
        $model = new \app\common\model\Question();
        $this->setAdminCurItem('add');
        if (!request()->isPost()) { // 点击添加页面
            $class = new Goodsclass();
            $parent_class_list = $class->getGoodsclassList(['gc_parent_id'=>0]);
            $this->assign('class_list',$parent_class_list);

            return $this->fetch('add');
        }
        $option = input('post.option', 0);
        $option = trim($option, ',');
        $data = [
            'title' => input('post.title', '', 'trim'),
            'gc_id1' => input('post.gc_id1', '', 'intval'),
            'shiyongshuoming' => input('post.shiyongshuoming'),
            'gc_id2' => input('post.gc_id2', '', 'intval'),
            'gc_id3' => input('post.gc_id3', '', 'intval'),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'option_id' => $option
        ];


        $question_validate = validate('question');
        if (!$question_validate->scene('add')->check($data)) {
            $this->error($question_validate->getError());
        }
        // 接收选项下的原因
        $option_answer = $request->post('option_answer/a');
        $option_answer_del = $request->post('option_answer_del/a');
        if (empty($option_answer)) $option_answer = [];
        if (empty($option_answer_del)) $option_answer_del = [];
        QuestionOption::addAnswer($option_answer);

        foreach ($option_answer as $key => $val) {
            \app\common\model\Answer::addOptionId($val, $key);
        }
        foreach ($option_answer_del as $key => $val) {
            \app\common\model\Answer::addOptionId($val, 0, 2);
        }
        $result = $model->addQuestion($data);
        QuestionOption::addQuestionId($option, $result);
        if ($result) {
            dsLayerOpenSuccess(lang('question_add_child_succ'));
        } else {
            $this->error(lang('question_add_child_fail'));
        }
    }

    /**
     * 编辑问题
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function edit(Request $request)
    {
        $id = input('get.question_id', '', 'intval');
        if (!$id) {
            return $this->error('参数错误');
        }
        $model = \app\common\model\Question::find($id);
        $this->setAdminCurItem('add');
        if (!$model) return $this->error('参数错误');

        if (!request()->isPost()) {
            $options_id = explode(',', $model->option_id);
            $options = QuestionOption::getOptionListByIds($options_id);
            $class = new Goodsclass();
            $parent_class_list = $class->getGoodsclassList(['gc_parent_id'=>0]);
            $this->assign('class_list',$parent_class_list);
            $this->assign('options', $options);
            $this->assign('model', $model);
            return $this->fetch('add');
        }
        $data = [
            'title' => input('post.title', ''),
            'option_id' => input('post.option', ''),
            'updated_at' => date('Y-m-d H:i:s'),
            'shiyongshuoming' => input('post.shiyongshuoming'),
            'gc_id1' => input('post.gc_id1', '', 'intval'),
            'gc_id2' => input('post.gc_id2', '', 'intval'),
            'gc_id3' => input('post.gc_id3', '', 'intval'),
        ];
        $check_data = array_merge(['id' => $id], $data);
        $question_validate = validate('question');
        if (!$question_validate->scene('edit')->check($check_data)) {
            $this->error($question_validate->getError());
        }
        // 接收选项下的原因
        $option_answer = $request->post('option_answer/a');
        $option_answer_del = $request->post('option_answer_del/a');
        if (empty($option_answer)) $option_answer = [];
        if (empty($option_answer_del)) $option_answer_del = [];

        QuestionOption::addAnswer($option_answer);
        foreach ($option_answer as $key => $val) {
            \app\common\model\Answer::addOptionId($val, $key);
        }
        foreach ($option_answer_del as $key => $val) {
            \app\common\model\Answer::addOptionId($val, 0, 2);
        }

        if (!$model->save($data)) {
            $this->error('修改失败');
        }



        dsLayerOpenSuccess(lang('修改成功'));


    }

    /**
     * 修改选项
     */
    public function updateOption()
    {
        $id = input('get.id', '0');
        if (!$id) return json(['code' => 0, 'message' => '参数错误']);
//        if (QuestionOption::uniqueOptionsByContent(input('post.content', ''))) return json(['code' => 0, 'message' => '该现象已存在']);

        $model = QuestionOption::find($id);
        if (!$model) return json(['code' => 0, 'message' => '参数错误']);

        $model->content = input('post.content', '');
        if ($model->save()) {
            return json(['code' => 10000, 'message' => '修改成功']);
        }
        return json(['code' => 0, 'message' => '修改失败']);
    }

    public function addOptionAnswer()
    {
        $content = input('post.content', '');
        $method = input('post.method', '');
        $del_method_id = input('post.delmethodid', '');
//        if (\app\common\model\Answer::uniqueAnswerByContent($content, $del_method_id)) return json(['code' => 0, 'message' => '该原因已存在']);
//        if (\app\common\model\Answer::uniqueMethodByContent($method, $del_method_id)) return json(['code' => 0, 'message' => '该处理方法已存在']);
        $answer = new \app\common\model\Answer();

        $answer->content = input('post.content', '');
        $answer->method = input('post.method', '');

        $answer->created_at = date('Y-m-d H:i:s');
        $answer->updated_at = date('Y-m-d H:i:s');
        if ($answer->save()) {
            return json(['code' => 10000, 'message' => '添加成功', 'data' => ['id' => $answer->id, 'method' => $answer->method]]);
        }
        return json(['code' => 0, 'message' => '添加失败']);

    }

    /**
     * 给答案添加处理方法，添加的是answer表中的method字段
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addMethod()
    {
        $id = input('get.id', '0');
        if (!$id) return json(['code' => 0, 'message' => '参数错误']);
        $content = input('post.content', '');
        $method = input('post.method', '');

        $answer = \app\common\model\Answer::find($id);
//        if (\app\common\model\Answer::uniqueAnswerByContent($content) && $answer->content != $content) return json(['code' => 0, 'message' => '该原因已存在']);
//        if (\app\common\model\Answer::uniqueMethodByContent($method) && $answer->method != $method) return json(['code' => 0, 'message' => '该处理方法已存在']);
        if ($answer->content == $content && $answer->method == $method) return json(['code' => 0, 'message' => '未作任何修改']);
        if (!$answer) return json(['code' => 0, 'message' => '参数错误']);

        $answer->method = input('post.method', '');
        $answer->content = input('post.content', '');
        if (!$answer->save()) {
            return json(['code' => 0, 'message' => '添加失败']);
        }
        return json(['code' => 10000, 'message' => '添加成功', 'data' => ['id' => $answer->id, 'content' => $answer->content, 'method' => $answer->method]]);
    }
    public function getClass(){
        $gc_id = intval($_GET['gc_id']);
        $class = new Goodsclass();
        $class_list = $class->getGoodsclassList(['gc_parent_id'=>$gc_id]);
        echo json_encode($class_list);

    }

    public function addOption()
    {
        $content = input('post.option', '');
        $parent_id = input('get.parent_id', '0');
        $lev = input('post.lev', '0'); // 级别
        if (empty($content)) return json_encode(['code' => 0, 'message' => '参数不能为空']);
//        if (QuestionOption::uniqueOptionsByContent($content)) return json(['code' => 0, 'message' => '该现象已存在']);
        // 判断是否存在删除的里边了
        $del = input('post.deloption', '');
        if (is_string($del)) {
            $del = explode(',', trim($del, ','));
        }
        $options = QuestionOption::where('content', '=', $content)->select();
//        dump($del);
        $option = new QuestionOption();
        $isfalse = true;
        foreach ($options as $key => $val) {
//            dump($val['id']);
            if (in_array($val['id'], $del)) {
                $option = $val;
                $isfalse = false;
                break;
            }
        }
//        if ($options && $isfalse) return json(['code' => 0, 'message' => '该现象已存在']);


        $option->parent_id = $parent_id;
        $option->lev = $lev;
        $option->content = $content;
        $option->created_at = date('Y-m-d H:i:s');
        $option->updated_at = date('Y-m-d H:i:s');
        if (!$option->save()) {
            return json(['code' => 0, 'message' => '添加失败']);
        }
        return json(['code' => 10000, 'message' => '添加成功', 'data' => ['id' => $option->id, 'lev' => $option->lev]]);
    }

    public function option(Request $request)
    {
        $id = input('get.question_id', '');
        $model = \app\common\model\Question::find($id);
        if (!$model) {
            $this->error('参数错误');
        }
        if (!request()->isPost()) {
            // 查找问题下的所有选项
            $option_id = explode(',', $model->option_id);
            $options = QuestionOption::where('id', 'in', $option_id)->select();
            //查询所有问题
            $questions = [];
            $questions = \app\common\model\Question::all();
            $this->assign('questions', $questions);
            $this->assign('model', $model);
            $this->assign('options', $options);
            return $this->fetch('option');
        }

        $options_arr = $request->post('options/a');
        $next_question_arr = $request->post('next_question/a');
        // 批量选项关联跳转问题
        foreach ($options_arr as $key => $val) {
            $option = QuestionOption::find($val);
            if ($option) {
                $option->next_question = $next_question_arr[$key];
                if (!$option->save()) {
//                    $this->error('关联失败');
                }
            }
        }
        dsLayerOpenSuccess(lang('设置成功'));

    }

    public function stopQuestion()
    {
        $id = input('get.id', '0');
        if (!$id) return json(['code' => 0, 'message' => '参数错误1']);
        $model = \app\common\model\Question::find($id);
        if (!$model) return json(['code' => 0, 'message' => '参数错误']);
        $model->status = $model->status == 1 ? 0 : 1;
        if ($model->save()) {
            return json(['code' => 10000, 'message' => '修改成功']);
        }
        return json(['code' => 0, 'message' => '修改失败']);
    }

    /**
     * 删除父类问题
     */
    public function deleteParent()
    {
        $id = input('get.id', '', 'intval');
        $parent_id = input('get.parent_id', '', 'intval');
        if (\app\common\model\Question::deleteParentId($id, $parent_id)) {
            return json_encode(['error' => 0, 'msg' => '删除成功']);
        } else {
            return json_encode(['error' => -1, 'msg' => '删除失败']);
        }
    }

    protected function getAdminItemList() {
        $menu_array = array(
            array(
                'name' => 'index',
                'text' =>lang('ds_manage'),
                'url' => url('question/index')
            ),
            array(
                'name' => 'add',
                'text' => lang('ds_new'),
                'url' =>url('Question/add',['id'=>0]),
            ),
            /*array(
                'name' => 'edit',
                'text' => lang('ds_edit'),
                'url' =>url("question/question_class_edit"),
            )*/
        );
        return $menu_array;
    }



    /**
     * 添加子类问题方法
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function addChild()
    {
        $parent_id = input('get.parent_id', '', 'intval');
        $model = \app\common\model\Question::get($parent_id); // 父类问题
        if (empty($model)) {
            $this->error(lang('param_error'));
        }
        if (!request()->isPost()) { // 点击添加页面
            $class = new Goodsclass();
            $parent_class_list = $class->getGoodsclassList(['gc_parent_id'=>0]);
            $this->assign('class_list',$parent_class_list);
            $this->assign('model', $model);
            return $this->fetch('add');
        }

        $data = [
            'title' => input('post.title', '', 'trim'),
            'gc_id1' => input('post.gc_id1', '', 'intval'),
            'gc_id2' => input('post.gc_id2', '', 'intval'),
            'gc_id3' => input('post.gc_id3', '', 'intval'),
        ];
        $check_data = array_merge(['parent_id' => $parent_id], $data);


        $question_validate = validate('question');
        if (!$question_validate->scene('add_child')->check($check_data)) {
            $this->error($question_validate->getError());
        }
        $result = \app\common\model\Question::addChildQuestion($data, $parent_id);
        if ($result) {
            dsLayerOpenSuccess(lang('question_add_child_succ'));
        } else {
            $this->error(lang('question_add_child_fail'));
        }

    }

    public function delete()
    {
        $id = input('get.id', '', 'intval');
        // 判断是否有子问题
        if (\app\common\model\Question::hasNextQuestions($id)) {
            return json_encode(['code' => 0, 'message' => '有关联子问题，请先解除关系后删除']);
        }
        if (!\app\common\model\Question::destroy($id)) {
            return json_encode(['code' => 0, 'message' => '删除失败']);
        }
        return json_encode(['code' => 10000, 'message' => '删除成功']);
    }

    /**
     * 添加答案
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addAnswer()
    {
        $question_id = input('get.question_id', '', 'intval');
        if (!request()->isPost()) { // 点击添加答案页面
            // 查询所有未关联的答案
            $answer_list = \app\common\model\Question::getAnswerList($question_id);
            // 查询关联的所有答案
            $answer = \app\common\model\Question::getAnswer($question_id);
            $this->assign('question_id', $question_id);
            $this->assign('answer', $answer);
            $this->assign('answer_list', $answer_list);
            return $this->fetch('add_answer');
        }
        $content = input('post.content');
        if (empty($content)) {
            return json_encode(['code' => 0, 'message' => '内容不能为空']);
        }
        $answer = new \app\common\model\Answer();
        $answer->content = $content;
        $answer->created_at = date('Y-m-d H:i:s');
        $answer->updated_at = date('Y-m-d H:i:s');
        if (!$answer->save()) {
            return json_encode(['code' => 0, 'message' => '内容添加失败']);
        }
        if (!\app\common\model\Question::addAnswer($question_id, $answer->id)) {
            return json_encode(['code' => 0, 'message' => '关联答案失败']);
        }
        return json_encode(['code' => 10000, 'message' => '添加成功', 'id' => $answer->id]);
    }

    /**
     * 删除问题与答案的关联
     * @return string
     */
    public function deleteAnswer()
    {
        $question_id = input('get.question_id', '', 'intval');
        $answer_id = input('get.answer_id', '', 'intval');
        if (\app\common\model\Question::deleteAnswer($question_id, $answer_id)) {
            return json_encode(['code' => 10000, 'message' => '删除成功']);
        } else {
            return json_encode(['code' => 0, 'message' => '删除失败']);
        }

    }

    public function AddAnswerSelect()
    {
        $question_id = input('get.question_id', '', 'intval');
        $answer_id = input('get.answer_id', '', 'intval');
        if (\app\common\model\Question::addAnswer($question_id, $answer_id)) {
            return json_encode(['code' => 10000, 'message' => '添加成功']);
        } else {
            return json_encode(['code' => 0, 'message' => '添加失败', 'id' => $answer_id]);
        }
    }
}
